<template>
  <el-form
    :model="queryParams"
    ref="queryForm"
    size="small"
    :inline="true"
    label-width="68px"
  >
    <template v-for="(f, i) in searchFields">
      <el-form-item :label="f.label" :prop="f.code" :key="i">
        <el-select
          v-if="f.type == 'radio' || f.type == 'checkbox'"
          v-model="queryParams[f.code]"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="dict in dataOptions[f.code]"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>

       <el-select
            v-else-if="f.type == 'select'"
            v-model="queryParams[f.code]"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="dict in dataOptions[f.code]"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>

        <treeselect v-else-if="f.type == 'tree'"
          v-model="queryParams[f.code]"
          :options="dataOptions[f.code]"
          style="width: 200px"
          :normalizer="normalizer"
          placeholder="请选择"
        />

        <el-date-picker v-else-if="f.type == 'date' || f.type == 'datetime'"
          v-model="queryParams[f.code]"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>

        <el-input v-else
          v-model="queryParams[f.code]"
          :placeholder="'请输入' + f.label"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
    </template>
    <el-form-item v-if="searchFields.length > 0">
      <el-button
        type="primary"
        icon="el-icon-search"
        size="mini"
        @click="handleQuery"
        >搜索</el-button
      >
      <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
        >重置</el-button
      >
    </el-form-item>
  </el-form>
</template>

<script>
import { apiGet, apiDs } from "@/api/openapi";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "SearchForm",
  components: {    Treeselect  },
  dicts: [],
  props: {
    //字段列表模型
    fields: Array,
  },
  data() {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      queryParams: {},
      searchFields: [],
      dataOptions: {}
    };
  },
  created() {
    this.initField();
  },
  methods: {
    initField() {
      let params = {"@exp":{}};
      let ps = [];
      for (var i = 0; i < this.fields.length; i++) {
        if (!this.fields[i].search || this.fields[i].search == '0') {
          continue;
        }
        let field = {...this.fields[i]};
        params[field.code] = null;
        params["@exp"][field.code] = field.search;
        
        if (field.type == "radio" || field.type == "checkbox") {
          ps.push(new Promise((resolve, reject) =>{
            apiDs('sys_dict_select',{dict:field.ds}).then((res) => {
              this.dataOptions[field.code] = res.data;
              resolve();
            });
          }));
          
        } else if (field.type == "select") {
          this.dataOptions[field.code] = [];
          ps.push(new Promise((resolve, reject) =>{
            apiDs(field.ds).then((res) => {
              this.dataOptions[field.code] = res.data;
              resolve();
            });
          }));
        } else if (field.type == "tree") {
          this.dataOptions[field.code] = [];
          ps.push(new Promise((resolve, reject) =>{
            apiDs(field.ds).then((res) => {
              this.dataOptions[field.code] = this.handleTree(res.data, 'value', 'pid');
              resolve();
            });
          }));
        } else if (field.type == "date" || field.type == 'datetime') {
          params[field.code] = [];
        }
        this.searchFields.push(field);
      }
      if(ps.length > 0){
        Promise.all(ps).then(res=>{
          this.$forceUpdate();
        })
      }
      this.queryParams = params;
    },
    /** 转换资产分类数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.value,
        label: node.label,
        children: node.children,
      };
    },
    /** 取消按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.$emit("cancel");
    },
    // 搜索按钮
    handleQuery() {
      this.$emit("submit", this.queryParams);
    },
  },
};
</script>
<!--
搜索条件：
1、普通输入文本/数字,不支持长文本
2、日期/日期时间自动转换成范围搜索
3、图片上传/文件上传，不支持搜索
4、字典内容支持多选和单选都转换成单选下拉搜索
5、其它业务数据单选和树形下拉，需要指定数据源，只做单选
6、扫码枪：如果未配置数据源，直接将扫码结果作为当前值；如果配置数据源，会用code作为参数去数据源取值，返回是的id作为当前数据
--!>